package com.bys.transaction;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * JDBC 事务管理器
 * @author bys
 * @version 1.0
 * @since 1.0
 */
public class JDBCTransaction implements Transaction{
    /**
     * 数据源对象
     */
    private DataSource dataSource;
    /**
     * 是否自动自己提交
     */
    private boolean autoCommit;
    /**
     * 连接对象
     */
    private Connection connection;

    public JDBCTransaction(DataSource dataSource, boolean autoCommit) {
        this.dataSource = dataSource;
        this.autoCommit = autoCommit;
    }

    public Connection getConnection() {
        return connection;
    }

    @Override
    public void commit() {
        try {
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void rollback() {
        try {
            connection.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void close() {
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void openConnection() {
        if(connection == null) {
            try {
                connection = dataSource.getConnection();
                connection.setAutoCommit(false);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
